package com.serkol.ams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serkol.ams.entity.*;
import com.serkol.ams.mapper.AgentInvitationRelationshipMapper;
import com.serkol.ams.modal.SqlFeildModal;
import com.serkol.ams.service.AgentInvitationRelationshipLogService;
import com.serkol.ams.service.AgentInvitationRelationshipService;
import com.serkol.ams.service.UsersService;
import com.serkol.ams.service.UsersWalletService;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultCode;
import com.serkol.exception.AuthException;
import com.serkol.handler.MyLambdaQueryWrapper;
import com.serkol.utils.SwitchUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author pingan
 * @description 针对表【agent_invitation_relationship】的数据库操作Service实现
 * @createDate 2022-09-23 12:31:50
 */
@Service
public class AgentInvitationRelationshipServiceImpl extends ServiceImpl<AgentInvitationRelationshipMapper, AgentInvitationRelationship>
        implements AgentInvitationRelationshipService {
    @Autowired
    private AgentInvitationRelationshipLogService logService;

    @Autowired
    private UsersWalletService walletService;
    @Autowired
    private UsersService usersService;

    @Transactional
    @Override
    public boolean getInvitationRelationship(OrderMaster order, long agentId) throws AuthException {
        LoginLog loginLog = AuthConstant.getLoginLog();
        Users byUserId = usersService.findByUserId(loginLog.getParentUserId());

        if (byUserId != null) {
            LambdaQueryWrapper<AgentInvitationRelationship> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AgentInvitationRelationship::getAgentId, agentId);
            queryWrapper.eq(AgentInvitationRelationship::getRelationAgentId, byUserId.getAgentId());
            AgentInvitationRelationship one = this.getOne(queryWrapper);
            if (one != null) {
                AgentInvitationRelationshipLog log = new AgentInvitationRelationshipLog();
                log.setAgentId(agentId);
                log.setRelationAgentId(byUserId.getAgentId());
                log.setOrderId(order.getId());
                log.setUserId(loginLog.getUserId());
                log.setRelationUserId(loginLog.getParentUserId());
                log.setPrice(one.getPrice());
                log.setType(1);
                boolean save = logService.save(log);
                if (save) {
                    boolean wsave = walletService.reChange(loginLog.getParentUserId(), one.getPrice(), 1);
                    if (wsave) {
                        return true;
                    } else {
                        throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
                    }
                } else {
                    throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
                }

            } else {
                throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
            }
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
        }


    }

    @Override
    public boolean getCreateInvitationRelationship(OrderMaster order) throws AuthException {
        LoginLog loginLog = AuthConstant.getLoginLog();
        Users byUserId = usersService.findByUserId(loginLog.getParentUserId());
        if (byUserId != null) {
            LambdaQueryWrapper<AgentInvitationRelationship> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AgentInvitationRelationship::getAgentId, loginLog.getAgentId());
            queryWrapper.eq(AgentInvitationRelationship::getRelationAgentId, byUserId.getAgentId());
            AgentInvitationRelationship one = this.getOne(queryWrapper);
            if (one != null) {
                Map<Integer, Users> userList = usersService.getParentUsersLevel(byUserId);
                //通过 lambda 表达式使用 forEach()
                AtomicBoolean flag = new AtomicBoolean(false);
                userList.forEach((key, value) -> {
                    switch (key) {
                        case 1:
                            flag.set(createOrder(order.getId(), value, one.getLevel1()));
                            break;
                        case 2:
                            flag.set(createOrder(order.getId(), value, one.getLevel2()));
                            break;
                        case 3:
                            flag.set(createOrder(order.getId(), value, one.getLevel3()));
                            break;
                    }
                });
                return flag.get();
            } else {
                throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
            }
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
        }
    }


    private boolean createOrder(long orderId, Users byUserId, BigDecimal price) {
        if (price != null && price.intValue() > 0) {
            LoginLog loginLog = AuthConstant.getLoginLog();
            AgentInvitationRelationshipLog log = new AgentInvitationRelationshipLog();
            log.setAgentId(loginLog.getAgentId());
            log.setRelationAgentId(byUserId.getAgentId());
            log.setOrderId(orderId);
            log.setUserId(loginLog.getUserId());
            log.setRelationUserId(loginLog.getParentUserId());
            log.setPrice(price);
            log.setType(0);
            System.out.println(log.toString());
            System.out.println("PRICE:" + price);
            boolean save = logService.save(log);
            if (save) {
                boolean wsave = walletService.reChange(loginLog.getParentUserId(), price, 2);
                if (wsave) {
                    return true;
                } else {
                    //  throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
                    return false;
                }
            } else {
                // throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public List<Long> findByGoodsIds(long agentId) {
        QueryWrapper<AgentInvitationRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("GOODS_ID");
        queryWrapper.lambda().isNotNull(AgentInvitationRelationship::getGoodsId);
        List<Object> objects = this.listObjs(queryWrapper);
        return SwitchUtil.objToList(objects, Long.class);
    }

    @Override
    public boolean getCreateInvitationRelationshipOne(List<OrderDetail> goodsByList, List<OrderDetail> goodsByList1) throws AuthException {
        LoginLog loginLog = AuthConstant.getLoginLog();
        Users byUserId = usersService.findByUserId(loginLog.getParentUserId());
        if (byUserId != null) {
            AtomicBoolean flag = new AtomicBoolean(false);
            Iterator<OrderDetail> iterator = goodsByList.iterator();
            while (iterator.hasNext()) {
                OrderDetail next = iterator.next();
                boolean createInvitationRelationshipOn = getCreateInvitationRelationshipOn(byUserId, next);
                flag.set(createInvitationRelationshipOn);
            }
            Iterator<OrderDetail> iterator1 = goodsByList1.iterator();
            while (iterator1.hasNext()) {
                OrderDetail next = iterator1.next();
                boolean createInvitationRelationshipOn = getCreateInvitationRelationshipOn(byUserId, next);
                flag.set(createInvitationRelationshipOn);
            }
            return flag.get();
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
        }
    }


    @Override
    public List<Map<String, Object>> findByList(int state, boolean isActivty) {
        QueryWrapper<AgentInvitationRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.AgentInvitationRelationshipFeild());
        queryWrapper.lambda().orderByAsc(AgentInvitationRelationship::getState).orderByDesc(AgentInvitationRelationship::getAgentId).orderByDesc(AgentInvitationRelationship::getRelationAgentId);
        if (state > 0) {
            queryWrapper.lambda().eq(AgentInvitationRelationship::getIsActivty, isActivty).eq(AgentInvitationRelationship::getState, state);
        } else {
            if (isActivty) {
                queryWrapper.lambda().eq(AgentInvitationRelationship::getIsActivty, true);
            }
        }
        List<Map<String, Object>> maps = this.baseMapper.selectMaps(queryWrapper);
        return maps;
    }

    @Override
    public List<Map<String, Object>> findByCategoryIdList(long categoryId, int state, boolean isActivty) {
        QueryWrapper<AgentInvitationRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.AgentInvitationRelationshipFeild());
        queryWrapper.lambda().eq(AgentInvitationRelationship::getCategoryId, categoryId).orderByAsc(AgentInvitationRelationship::getState).orderByDesc(AgentInvitationRelationship::getAgentId).orderByDesc(AgentInvitationRelationship::getRelationAgentId);
        if (state > 0) {
            queryWrapper.lambda().eq(AgentInvitationRelationship::getIsActivty, isActivty).eq(AgentInvitationRelationship::getState, state);
        } else {
            if (isActivty) {
                queryWrapper.lambda().eq(AgentInvitationRelationship::getIsActivty, true);
            }
        }
        return this.baseMapper.selectMaps(queryWrapper);
    }


    @Override
    public boolean valid(AgentInvitationRelationship agent) {
        MyLambdaQueryWrapper<AgentInvitationRelationship> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eqAgentCategory(AgentInvitationRelationship::getCategoryId);
        queryWrapper.eq(AgentInvitationRelationship::getAgentId, agent.getAgentId()).eq(AgentInvitationRelationship::getRelationAgentId, agent.getRelationAgentId()).eq(AgentInvitationRelationship::getGoodsId, agent.getGoodsId());


        return this.baseMapper.exists(queryWrapper);
    }

    @Override
    public AgentInvitationRelationship getAgentInfo(long agentId, long relationAgentId, Integer isActivty, int type) {
        MyLambdaQueryWrapper<AgentInvitationRelationship> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(AgentInvitationRelationship::getAgentId, agentId).eq(AgentInvitationRelationship::getRelationAgentId, relationAgentId).eq(AgentInvitationRelationship::getIsActivty, isActivty).isNull(AgentInvitationRelationship::getGoodsId);
        queryWrapper.eqAgentCategory(AgentInvitationRelationship::getCategoryId);
        if (type > -1) {
            queryWrapper.eq(AgentInvitationRelationship::getState, type);
        }

        queryWrapper.last("limit 1");

        return this.getOne(queryWrapper);
    }

    @Override
    public AgentInvitationRelationship getAgentInfoImpl(Long agentId, Long relationAgentId, Integer isActivty, Long goodsId, int type) {
        System.out.println("TYPE:-----------------:" + type);
        MyLambdaQueryWrapper<AgentInvitationRelationship> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(AgentInvitationRelationship::getAgentId, agentId).eq(AgentInvitationRelationship::getRelationAgentId, relationAgentId).eq(AgentInvitationRelationship::getIsActivty, isActivty).eq(AgentInvitationRelationship::getGoodsId, goodsId);
        queryWrapper.eqAgentCategory(AgentInvitationRelationship::getCategoryId);
        if (type > -1) {
            queryWrapper.eq(AgentInvitationRelationship::getState, type);
        }
        queryWrapper.last("limit 1");
        if (this.baseMapper.exists(queryWrapper)) {
            return this.getOne(queryWrapper);
        } else {
            MyLambdaQueryWrapper<AgentInvitationRelationship> queryWrapper1 = new MyLambdaQueryWrapper<>();
            queryWrapper1.eq(AgentInvitationRelationship::getAgentId, agentId).eq(AgentInvitationRelationship::getRelationAgentId, relationAgentId).eq(AgentInvitationRelationship::getIsActivty, isActivty).isNull(AgentInvitationRelationship::getGoodsId);
            queryWrapper1.eqAgentCategory(AgentInvitationRelationship::getCategoryId);
            if (type > -1) {
                queryWrapper1.eq(AgentInvitationRelationship::getState, type);
            }
            queryWrapper1.last("limit 1");
            return this.getOne(queryWrapper1);
        }

    }

    @Override
    public AgentInvitationRelationship findByAgentInValidConfig(long agentId) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        QueryWrapper<AgentInvitationRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AgentInvitationRelationship::getUpgradeAgentId, agentId).eq(AgentInvitationRelationship::getCurrentUpgradeAgentId, loginLog.getAgentId());

        queryWrapper.last("limit 1");
        AgentInvitationRelationship one = this.getOne(queryWrapper);
        return one;
    }

    @Override
    public AgentInvitationRelationship getAgentUpgradeInfo(Long parentAgentId, Long agentId, long agentId1, Integer isActivty, int type) {
        MyLambdaQueryWrapper<AgentInvitationRelationship> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(AgentInvitationRelationship::getUpgradeAgentId, agentId1).eq(AgentInvitationRelationship::getCurrentUpgradeAgentId, agentId).isNull(AgentInvitationRelationship::getGoodsId);
        queryWrapper.eq(AgentInvitationRelationship::getAgentId, parentAgentId).eq(AgentInvitationRelationship::getIsActivty, isActivty);
        queryWrapper.eqAgentCategory(AgentInvitationRelationship::getCategoryId);
        if (type > -1) {
            queryWrapper.eq(AgentInvitationRelationship::getState, type);
        }
        queryWrapper.last("limit 1");

        return this.getOne(queryWrapper);
    }


    private boolean getCreateInvitationRelationshipOn(Users byUserId, OrderDetail detail) throws AuthException {
        LoginLog loginLog = AuthConstant.getLoginLog();
        MyLambdaQueryWrapper<AgentInvitationRelationship> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(AgentInvitationRelationship::getAgentId, loginLog.getAgentId());
        queryWrapper.eq(AgentInvitationRelationship::getRelationAgentId, byUserId.getAgentId());
        queryWrapper.eqAgentCategory(AgentInvitationRelationship::getCategoryId);
        AgentInvitationRelationship one = this.getOne(queryWrapper);
        if (one != null) {
            Map<Integer, Users> userList = usersService.getParentUsersLevel(byUserId);
            //通过 lambda 表达式使用 forEach()
            AtomicBoolean flag = new AtomicBoolean(false);
            userList.forEach((key, value) -> {
                switch (key) {
                    case 1:
                        BigDecimal level1 = one.getLevel1();
                        level1 = level1.multiply(BigDecimal.valueOf(detail.getQuantity()));
                        flag.set(createOrder(detail.getOrderId(), value, level1));
                        break;
                    case 2:
                        BigDecimal level2 = one.getLevel1();
                        level2 = level2.multiply(BigDecimal.valueOf(detail.getQuantity()));
                        flag.set(createOrder(detail.getOrderId(), value, level2));
                        break;
                    case 3:
                        BigDecimal level3 = one.getLevel1();
                        level3 = level3.multiply(BigDecimal.valueOf(detail.getQuantity()));
                        flag.set(createOrder(detail.getOrderId(), value, level3));
                        break;
                }
            });
            return flag.get();
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
        }

    }


}




